package com.jinxin.platform.cdacsrecord.core.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.*;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonCodeEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.DataResult2;
import com.jinxin.platform.cdacsrecord.core.service.*;
import com.jinxin.platform.cdacsrecord.core.utils.DateUtil;
import com.jinxin.platform.cdacsrecord.core.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-07-31
 * @Author: Lingnan
 **/
@RestController
@RequestMapping("/unAuth/openRecord")
@Slf4j
public class OpenRecordController {
    @Autowired
    private JurenAcsCommunityService acsCommunityService;
    @Autowired
    private RestTemplateService restTemplateService;
    @Autowired
    private JurenAcsOpenRecordService openRecordService;
    @Autowired
    private AcsControlUserInfoService userInfoService;
    @Autowired
    private AcsControlBlockInfoService blockInfoService;
    @Autowired
    private AcsControlRoomInfoService roomInfoService;

    @RequestMapping("listUsersByCondition")
    public JsonResult listUsersByCondition(@RequestBody(required = false) AcsControlUserInfoDO userInfoDO){
        if(userInfoDO == null){
            return JsonResult.error("参数不存在");
        }
        int page = userInfoDO.getPageNum() != null ? userInfoDO.getPageNum() : 1;
        int size = userInfoDO.getPageSize() != null ? userInfoDO.getPageSize() : 10;
        PageHelper.startPage(page,size);
        List<AcsControlUserInfoDO> userList = userInfoService.selDOByInfo(userInfoDO,userInfoDO.getBlockIds());
        PageInfo<AcsControlUserInfoDO> pageInfo = new PageInfo<>(userList);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("count",pageInfo.getTotal());
        resultMap.put("data",pageInfo.getList());
        return JsonResult.ok(resultMap);
    }

    @RequestMapping("listRoomsByBlockId")
    public JsonResult listRoomsByBlockId(String blockId){
        if(StringUtils.isEmpty(blockId)){
            return JsonResult.error("楼栋id为空");
        }
        AcsControlRoomInfoDO roomInfoDO = new AcsControlRoomInfoDO();
        if(!StringUtils.isEmpty(blockId)){
            roomInfoDO.setBlockId(blockId);
        }
        List<AcsControlRoomInfoDO> infoDOS = roomInfoService.selDOByInfo(roomInfoDO);
        return JsonResult.ok(infoDOS);
    }

    @RequestMapping("listStatBlcokInfo")
    public JsonResult listStatBlcokInfo(String companyId){
        if(StringUtils.isEmpty(companyId)){
            return JsonResult.error("小区id不能为空");
        }
        return JsonResult.ok(blockInfoService.listStatBlcokInfo(companyId));
    }

    @RequestMapping("listCommunities")
    public JsonResult listCommunities(){
        return JsonResult.ok(acsCommunityService.listCommunities());
    }

    @GetMapping("/listTimeCountData")
    public JsonResult listTimeCountData(@RequestParam String phone, @RequestParam String startDate,
                                        @RequestParam String endDate){
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)){
            return JsonResult.error("参数错误");
        }
        HashMap param2 = new HashMap();
        param2.put("userPhone",phone);
        AcsControlUserInfoDO userInfoDO = userInfoService.selectOne(param2);
        if(userInfoDO == null){
            return JsonResult.error("未查询该手机号的用户信息");
        }
        HashMap param = new HashMap();
        param.put("wyUserName", userInfoDO.getUserName());
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        List list = openRecordService.listTimeCountData(param);
        return JsonResult.ok(list);
    }

    @RequestMapping("/listByPhone")
    public Map<String,Object> listByPhone(@RequestParam Integer page, @RequestParam Integer limit,
                                   String phone, String startDate,String endDate){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code",0);
        String msg;
        int pageNum = page != null ? page : 1;
        int limitNum = limit != null ? limit : 10;
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)){
            resultMap.put("msg", "参数错误");
            resultMap.put("count",0);
            resultMap.put("data",null);
            return resultMap;
        }
        HashMap param2 = new HashMap();
        param2.put("userPhone",phone);
        AcsControlUserInfoDO userInfoDO = userInfoService.selectOne(param2);
        int count = 0;
        List<JurenAcsOpenRecord> dataList = null;
        if(userInfoDO == null){
            msg = "未查询该手机号的用户信息";
        }else {
            HashMap param = new HashMap();
            param.put("page", pageNum);
            param.put("limit", limitNum);
            param.put("wyUserName", userInfoDO.getUserName());
            param.put("startDate", startDate);
            param.put("endDate", endDate);
            count = openRecordService.listPageCount(param);
            dataList = openRecordService.listPage(param);
            msg = "success";
        }
        resultMap.put("msg", msg);
        resultMap.put("count",count);
        resultMap.put("data",dataList);
        return resultMap;
    }

    @RequestMapping("/list")
    public Map<String,Object> list(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit,
                                   JurenAcsOpenRecord recordParam,String companyId,
                                   String startDate,String endDate,String gateLocakName){
        HashMap param = Utils.transformBean2HashMap(recordParam);
        param.put("page",  page != null ? page : 1);
        param.put("limit", limit != null ? limit : 10);
        param.put("gateLocakName",gateLocakName);
//        if(recordParam != null){
//            param.put("areaId", recordParam.getAreaId());
//            param.put("gateLocakName", recordParam.getGateLocakName());
//            param.put("wyUserType", recordParam.getWyUserType());
//            param.put("wyUserId", recordParam.getWyUserId());
//        }
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        param.put("companyId", companyId);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code",0);
        resultMap.put("msg","");
        resultMap.put("count",openRecordService.listPageCount(param));
        resultMap.put("data",openRecordService.listPage(param));
        return resultMap;

    }

    @PostMapping("updateData")
    public ResultEntity updateData(String companyId,String startDate, String endDate){
        return openRecordService.updateData(companyId,startDate,endDate);
    }

    // 获取开门的统计信息，出入流量和访客数量统计
    @GetMapping("/getOpenStatistics")
    public JsonResult getOpenStatistics(String companyId){
//        OpenRecordParam recordParam = new OpenRecordParam();
//        recordParam.setPage(1);
//        recordParam.setRows(10000);
        Map<String,Object> resultMap = new HashMap<>();
//        ResultEntity resultEntity = restTemplateService.listOpenRecord(recordParam,companyId);
//        long openCount = 0,visitorCount = 0;
//        if(resultEntity != null){
//            log.info("getOpenStatistics: " + resultEntity.toString());
//            DataResult2 dataResult = (DataResult2)resultEntity.getResultContent();
//            openCount = dataResult.getRecords() != null ? dataResult.getRecords() : 0;
//            JSONArray jsonArray = dataResult.getRows();
//            if(jsonArray != null){
//                List<Integer> listTemp = new ArrayList();
//                for (int i = 0; i < jsonArray.size(); i++) {
//                    JSONObject jsonObject = jsonArray.getJSONObject(i);
//                    JurenOpenRecordInfo info = JSON.parseObject(JSON.toJSONString(jsonObject), JurenOpenRecordInfo.class);
//                    JSONObject wyUser = info.getWyUser();
//                    if(wyUser != null){
//                        WyUserInfo wyUserInfo = JSON.parseObject(JSON.toJSONString(wyUser), WyUserInfo.class);
//                        if(wyUserInfo != null){
//                            if(!listTemp.contains(wyUserInfo.getWyUserId())){
//                                listTemp.add(wyUserInfo.getWyUserId());
//                            }
//                        }
//                    }
//                }
//                visitorCount = listTemp.size();
//            }
//        }
        HashMap param = new HashMap();
        int openCount = openRecordService.listPageCount(param);
        resultMap.put("openCount", openCount);
        return JsonResult.ok(resultMap);
    }

    // 获取当天的开门次数
    @GetMapping("/statisOpenCountOfDay")
    public JsonResult statisticsOpenCount(String companyId){
        HashMap param = new HashMap();
        String startDate = DateUtil.getCurrentDayYMD()+" 00:00:00";
        String endDate = DateUtil.getCurrentDayYMD()+" 23:59:59";
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        param.put("companyId", companyId);
        int count = openRecordService.listPageCount(param);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("openCount", count);
        return JsonResult.ok(resultMap);
    }

    /**
     * 获取所有房间的用户信息
     * @return
     */
    @RequestMapping("/listRoomOwners")
    public JsonResult listRoomOwners(){
        log.info("=======获取所有房间的用户信息 listRoomOwners ");
        return JsonResult.ok(userInfoService.selectOwners());
    }

    /**
     * 获取所有的社区用户信息
     * @return
     */
    @RequestMapping("/listUsers")
    public JsonResult listUsersByCondition(){
        return JsonResult.ok(userInfoService.selectAllUsers());
    }

    @GetMapping("/getAkInfoByUser")
    public ResultEntity getAkInfoByUser(){
        return userInfoService.getAkInfoByUser();
    }

    @GetMapping("/getSyncfFrequency")
    public ResultEntity getSyncfFrequency(){
        return userInfoService.getSyncfFrequency();
    }

    @PostMapping("/saveAkInfo")
    public ResultEntity saveAkInfo(AppIdSecretInfo appIdSecretInfo){
        return userInfoService.saveOrUpdate(appIdSecretInfo);
    }

    @PostMapping("/saveSyncFre")
    public ResultEntity saveOrUpdateFre(DataSyncFrequency dataSyncFrequency){
        return userInfoService.saveOrUpdateFre(dataSyncFrequency);
    }
}
